package a01_数组;

/**
 * <p>
 * a05_螺旋矩阵2
 * </p>
 *
 * @author flyduck
 * @since 2024-06-13
 */
public class a06_螺旋矩阵2复习1 {

    public static void main(String[] args) {
        int[][] result = generateMatrix(2);
        for (int i = 0; i < result.length; i++) {
            for (int j = 0; j < result[i].length; j++) {
                System.out.print(result[i][j]+" ");
            }
            System.out.println();
        }
    }

    public static int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        //i表示将要赋值的元素
        result[0][0] = 1;
        int i = 2;
        String direction = "right";
        //x、y表示上一个已经赋值的坐标
        int x = 0;
        int y = 0;
        while (i <= n * n){
            if(direction.equals("right")){
                if(y + 1 < n && result[x][y+1] == 0){
                    result[x][y+1] = i;
                    i++;
                    y++;
                }else {
                    direction = "down";
                }
            }
            if(direction.equals("down")){
                if(x + 1 < n && result[x+1][y] == 0){
                    result[x+1][y] = i;
                    i++;
                    x++;
                }else {
                    direction = "left";
                }
            }

            if(direction.equals("left")){
                if(y - 1 >= 0 && result[x][y-1] == 0){
                    result[x][y-1] = i;
                    i++;
                    y--;
                }else {
                    direction = "up";
                }
            }

            if(direction.equals("up")){
                if(x - 1 >= 0 && result[x-1][y] == 0){
                    result[x-1][y] = i;
                    i++;
                    x--;
                }else {
                    direction = "right";
                }
            }
        }
        return result;
    }
}
